<template>
<div class="product">
    
    <!-- 搜索框 -->
    <div class="search">
      <el-select
        v-model="searchValue"
        clearable
        filterable
        remote
        reserve-keyword
        @clear="clear"
        @blur="searchBlur"
        @change="searchTextChange"
        placeholder="请输入关键词"
        :remote-method="remoteMethod"
        :loading="loading"
      >
        <el-option v-for="item in searchList" :key="item.sId" :label="item.name" :value="item.name"></el-option>
      </el-select>
      <!-- 搜索放大镜按钮 -->
      <el-button icon="el-icon-search" @click="searchButton"></el-button>
     <!-- 添加学员信息按钮 -->
      <el-button type="success" @click="addStuDetail" v-haspermission="'add'">新增学员信息</el-button>
    </div>

    <!-- 选择器 -->
    <template class="select">
      <el-form >
        <el-form-item label="选择班级">
          <el-select v-model="classForm" 
                     filterable
                     @visible-change="classVisible"
                     @change="searchClass"
                     
                     placeholder="请选择">
            <el-option label="全部"
                       value="all"                   
            ></el-option>
            <el-option
              v-for="item in options"
              :key="item"
              :label="item"
              :value="item"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
    </template>
    <template>
       <el-row>
        <el-button type="info" round @click="exportExcel">导出Excel表</el-button>
      </el-row>
    </template>
    
    <!-- 表格展示 -->
    <div>
      <template>
        <!-- data表示注入的数据 v-loading局部区域加载动画 -->
        <el-table
          :data="tableData"
          :border="true"
          v-loading="studentsTableLoading"
          style="width: 100%"
        >
          <el-table-column prop="headimgurl" label="头像" width="80">
            <!-- 通过 Scoped slot 可以获取到 row, column, $index 和 store（table 内部的状态管理）的数据 -->
            <template slot-scope="scope">
              <el-avatar shape="square" :size="50" fit="fill" :src="scope.row.headimgurl"></el-avatar>
            </template>
          </el-table-column>
          <!-- prop代表要渲染的内容 ，label代表表头名 -->
          <!-- 这里不循环创建是因为不需要这么多字段 -->
          <el-table-column prop="name" label="姓名" width="180"></el-table-column>
          <el-table-column prop="class" label="班级" width="180"></el-table-column>
          <el-table-column prop="degree" label="学历" width="180"></el-table-column>
          <el-table-column prop="productUrl" label="项目地址"></el-table-column>
          <el-table-column label="操作">
            <template slot-scope="scope">
              <!-- scope就相当于当前tableData的一行 -->
              <el-button size="mini" @click="$router.push({name:'studentProfile'})" v-haspermission="'read'">查看</el-button>
              <el-button size="mini" @click="handleEdit(scope.$index, scope.row)" v-haspermission="'edit'" >编辑</el-button>
              <el-button size="mini" type="danger" @click="handleDelete(scope.$index, scope.row)" v-haspermission="'delete'">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </template>
    </div>
    <!-- 分页器 -->
    <div class="page">
      <el-pagination background layout="prev, pager, next" :total="1000"></el-pagination>
    </div>

    <!-- 新增学员信息的模态框 -->
    <div>
      <!--  ref被用来给元素或子组件注册引用信息。引用信息将会注册在父组件的$refs对象上，
      如果在普通的DOM元素上使用，引用指向的就是DOM元素，如果用在子组件上，引用就是组件实例-->
      <el-dialog :title="dialogInfo.title" :visible.sync="dialogFormVisible">
        <el-form :model="stuForm" :rules="stuRules" ref="addStuRuleForm">
          <el-form-item label="头像">
            <el-upload
              class="uploadAvatar"
              action="http://chst.vip/students/uploadStuAvatar"
              list-type="picture"
              :on-success="uploadSuccess"
              :on-remove="removeAvatar"
              name="headimgurl"
              :multiple="false"
              :limit="1"
              ref="uploadAvatar"
            >
              <img v-if="imageUrl" :src="imageUrl" class="uploadAvatar" />
              <i class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
          </el-form-item>

          <el-form-item label="姓名" prop="name">
            <el-input v-model="stuForm.name" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="项目地址" prop="productUrl">
            <el-input v-model="stuForm.productUrl" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="班级" prop="class">
            <el-input v-model="stuForm.class" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="年龄" prop="age">
            <el-input v-model="stuForm.age" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="城市" prop="city">
            <el-input v-model="stuForm.city" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="学历" prop="degree">
            <el-input v-model="stuForm.degree" autocomplete="off"></el-input>
          </el-form-item>

          <el-form-item label="描述">
            <el-input v-model="stuForm.description" autocomplete="off"></el-input>
          </el-form-item>
        </el-form>

        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取 消</el-button>
          <el-button type="primary" @click="confirmClick('addStuRuleForm')">确 定</el-button>
        </div>
      </el-dialog>
    </div>
  </div>
</template>


<script>
import { getLoginLog, getStuList, delStu, searchStu, getClasses } from "@/api";
// import { editStu, addStu } from '../../../api';
import getExcel from "qf-export-excel"
const api = require("@/api");
// console.log(api);
export default {
  data() {
    return {
      params:{
        page:"",
        count:5,
        class:""
      },
      // datapage:" ",  //页码
      // dataCount:5,  //每页展示的数量
      //搜索框
      searchList: [],
      searchValue: [],
      list: [],
      loading: false,
      states: [],
      clear: "",
      options: [],
      blurSearchValue: "",

      //班级选择框
      classForm:{},
      options:[],

      dialogInfo: {
        //模态框名字
        title: "增加学员信息",
        requestName: "",
        editSuccessMsg: "增加成功",
        editErrorMsg: "增加失败"
      },
      dialogFormVisible: false, //是否显示表单模态框

      //用于复用dialogEvent传递的事件名字
      dialogEvents: "addStudentInfo",
      // 表格加载动画
      studentsTableLoading: false,
      value: "",
      imageUrl: "",
      stuTotal: 30,

      tableData: [],
      stuRules: {
        //设置字段是否是必填选项
        name: [{ required: true, message: "请输入名字", trigger: "blur" }],
        class: [{ required: true, message: "请输入班级", trigger: "blur" }],
        degree: [{ required: true, message: "请输入学历", trigger: "blur" }],
        city: [{ required: true, message: "请输入城市", trigger: "blur" }],
        productUrl: [
          { required: true, message: "请输入项目地址", trigger: "blur" }
        ],
        age: [{ required: true, message: "请输入年龄", trigger: "blur" }]
      },
      stuForm: {
        name: "",
        productUrl: "",
        // headimgurl:"",
        class: "",
        age: "",
        city: "",
        degree: "",
        description: ""
      }
    };
  },
  methods: {
    //导出excel表格
    exportExcel(){
      let titleList = [
        {
          title:"头像",
          key:"headimgurl"
        },
        {
          title:"姓名",
          key:"name"
        },
        {
          title:"班级",
          key:"class"
        },
        {
          title:"项目",
          key:"productUrl"
        }
      ]
      let dataSource = this.tableData;
      getExcel(titleList, dataSource, "学员数据")
    },
    //点击搜索按钮的方法
    searchButton() {
      //点击搜索按钮
      this.loading = true;
      let key = this.searchValue;
      searchStu(key)
        .then(res => {
          if (res.data && res.data.state) {
            console.log(res.data.data);
            // 更改表格数据对象
            this.tableData = res.data.data;
            // 表格加载动画
            this.studentsTableLoading = false;
            this.loading = false;
          } else {
            this.$message.warning("搜索失败");
          }
        })
        .catch(err => {
          this.$message.error("网络出错");
        });
    },
    //搜索框方法
    remoteMethod(query) {
      // console.log(query);
      // 键盘弹起的时候获取输入值 赋值第三方变量
      this.blurSearchValue = query;
      let key = query;
      searchStu(key).then(res => {
        if (res.data && res.data.state) {
          // console.log(res.data.data);
          this.searchList = res.data.data;
        }
      });
    },
    // 搜索框失去焦点的方法
    searchBlur() {
      // 搜索框失去焦点，保持输入框的内容
      this.searchValue = this.blurSearchValue;
    },
    // 搜索框选中值发生变化的方法
    searchTextChange(searchText) {
      // 打开表格加载动画
      this.studentsTableLoading = true 
      // console.log(searchText);
      //再次调用搜索接口
      let key = searchText;
      searchStu(key)
        .then(res => {
          if (res.data && res.data.state) {
            console.log(res.data.data);
            // 更改表格数据对象
            this.tableData = res.data.data;
            // 表格加载动画
            this.studentsTableLoading = false;
          } else {
            this.$message.warning("搜索失败");
          }
        })
        .catch(err => {
          this.$message.error("网络出错");
        });
    },

    //班级选择框
    //班级选择展开触发的事件
    classVisible(r){    //展开返回true，闭合返回false
      // console.log(r)
      if(r){
        return getClasses()
          .then(res => {
            // console.log(res.data);
            this.options = res.data.data
          })
      }
    },

    //班级选择时触发的方法
    searchClass(query){
     
      //传递为空时返回所有
      this.params= query === "all" ? {count:5} : {class:query, count:5}
      this.getStudents(this.params)
      console.log(this.params);
    },


    //点击增加学生信息按钮触发的方法
    addStuDetail() {
      // 1.弹出dialog
      this.dialogFormVisible = true;
      //更改dialog标题
      this.dialogInfo.title = "增加学员信息";
      // 3.更改方法
      this.dialogInfo.requestName = "addStu";
      //提示信息
      this.dialogInfo.editSuccessMsg = "增加成功";
      this.dialogInfo.editErrorMsg = "增加失败，缺少字段";
    },
    //点击上传头像成功
    uploadSuccess(r) {
      // console.log("上传成功");
      //上传成功，给stuForm添加一条headimgurl
      this.stuForm.headimgurl = r.headimgurl;
      console.log(r);
    },
    //取消上传的方法
    removeAvatar(r) {
      this.stuForm.headimgurl = "";
    },
    //获取学员信息
    getStudents(params) {
      //表格加载动画
      this.studentsTableLoading = true;
     
      getStuList(params).then(res => {
        if (res.data.state) {
          this.tableData = res.data.data;

          //关闭表格加载动画
          console.log(res.data);
          this.studentsTableLoading = false;
          //重新给stuTotal赋值
          //   this.stuTotal = res.data.total
        }
        // console.log(res);
      });
    },
    //删除学员信息
    handleDelete(index, row) {
      console.log(index, row);
      let sId = row.sId;
      console.log(sId);
      //让用户确认一下是否要删除该条信息
      this.$confirm("此操作将永久删除学员, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          //调用删除学员的方法
          delStu(sId).then(res => {
            // console.log(res.data.state);
            if (res.data && res.data.state) {
              // this.tableData.splice(index, 1);
              //重新获取数据
              this.getStudents();
              this.$message({
                type: "success",
                message: "删除成功!"
              });
            } else {
              this.$message({
                type: "info",
                message: "该消息已被删除"
              });
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    },
    //编辑更新学员信息
    handleEdit(index, row) {
      // 1.弹出dialog
      this.dialogFormVisible = true;
      // 2.数据回显
      //更改dialog标题
      this.dialogInfo.title = "修改学员信息";
      // console.log(row);
      this.stuForm = { ...row }; //这里row是引用数据类型，使用解构不会动态改变数据
      // 3.更改
      this.dialogInfo.requestName = "editStu";
      //提示信息
      this.dialogInfo.editSuccessMsg = "修改成功";
      this.dialogInfo.editErrorMsg = "修改失败";
    },
    //点击增加学员信息或者编辑信息的确定按钮的方法
    confirmClick(formName) {
      this.$refs[formName].validate(valid => {
        // console.log(valid)
        if (valid) {
          //本地校验通过 将信息提交到后台
          let data = this.stuForm;
           // console.log(data);

          api[this.dialogInfo.requestName](data)
            .then(res => {
              // console.log(res);
              if (res.data.state) {
                //让页面刷新 把得到的addstuForm对象unshift到students数组
                this.getStudents();
                //关闭模态框
                this.dialogFormVisible = false;
                this.$message({
                  type: "success",
                  message: this.dialogInfo.editSuccessMsg
                });
                //清空stuForm数据对象
                //修复编辑之后再添加会发生缺少字段的Bug,清除_id字段
                if (this.stuForm["_id"]) delete this.stuForm["_id"];
                Object.keys(data).forEach(key => (data[key] = ""));
                this.$refs["uploadAvatar"].clearFiles(); //清空上传文件
              } else {
                this.$message.warning(this.dialogInfo.editErrorMsg);
              }
            })
            .catch(err => {
              this.$message.error("登入过期，网络错误");
            });
        }
      });
    }
  },

  mounted() {
    this.getStudents(this.params)
  }  
}
</script>
<style scoped>
.s-select {
  display: inline-block;
  width: 100%;
}
/* 搜索框按钮 */
.el-button--default {
  margin-left: 10px;
}
/*增加学员信息的模态框*/

.el-dialog__body .el-form .el-form-item__label {
  color: red;
}
.el-dialog__body .el-input__inner {
  background-color: #fff;
  border: 1px solid #000;
}
.el-dialog__body .el-form-item__content .el-input {
  width: 60%;
}
.el-dialog__body .el-button--primary {
  width: 100%;
}
/* 底部分页器样式 */
.el-pagination {
  position: relative;
  margin-bottom: 0px;
  text-align: center;
}
</style>